package cn.com.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_member_pay_records;
import cn.com.api.entity.ApiT_shipper_account;
import cn.com.api.entity.ApiT_shops_pay_records;
import cn.com.api.entity.ApiT_stats;
import cn.com.api.entity.ApiT_user_admin;
import cn.com.api.mapper.ApiCashMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_member_pay_recordsMapper;
import cn.com.api.mapper.ApiT_shipper_accountMapper;
import cn.com.api.mapper.ApiT_shop_pay_recordsMapper;
import cn.com.api.mapper.ApiT_statsMapper;
import cn.com.api.mapper.ApiT_user_adminMapper;
import cn.com.api.service.ApiT_statsService;
import cn.com.api.service.impl.base.T_statsServiceImplBase;
import cn.com.util.ArithUtil;
import cn.com.util.DateUtil;
import cn.com.util.*;

/**
 * 
 **/
@Service
public class ApiT_statsServiceImpl extends T_statsServiceImplBase implements
		ApiT_statsService {
	@Autowired
	private ApiT_statsMapper apiT_statsMapper;
	@Autowired
	private ApiCashMapper cashMapper;
	@Autowired
	private ApiT_shipper_accountMapper apiT_shipper_accountMapper;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	@Autowired
	private ApiT_user_adminMapper apiT_user_adminMapper;
	@Autowired
	private ApiT_shop_pay_recordsMapper apiT_shop_pay_recordsMapper;
	@Autowired
	private ApiT_member_pay_recordsMapper apiT_member_pay_recordsMapper;

	@Override
	public List<Map<String, Object>> shopAccount(String name,String balance,String stime,String etime,String discount,String cityid) {
		return apiT_statsMapper.shopAccount(name, balance, stime, etime, discount, cityid);
	}

	@Override
	public Double cashSum(String shopid) {
		return cashMapper.cashSum(shopid);
	}

	@Override
	public Map<String, Object> searByCash(String shopid) {
		return apiT_statsMapper.searByCash(shopid);
	}

	@Override
	public List<ApiT_stats> shipperStatList(ApiT_stats conditions, PageInfo pageInfo) {
		conditions.setShipperStats(true);
		return apiT_statsMapper.shipperStatListPage(conditions,pageInfo);
	}

	@Override
	public List<ApiT_stats> shipperMonthStatList(ApiT_stats conditions, PageInfo pageInfo) {
		conditions.setShipperStats(true);
		return apiT_statsMapper.shipperMonthStatListPage(conditions, pageInfo);
	}

	@Override
	public List<ApiT_stats> shipperMonthBillingList(ApiT_stats conditions, PageInfo pageInfo) {
		return apiT_statsMapper.shipperMonthBillingListPage(conditions,pageInfo);
	}

	@Override
	@Transactional
	public boolean updateShipperMonthBillingStatusAndRemark(int stats_id, Integer status, String remark) {
		ApiT_stats newStats = new ApiT_stats();
		newStats.setStats_id(stats_id);
		newStats.setStatus(status);
		newStats.setRemark(remark);
		String checkTime = DateUtil.nowTimeToString();
		newStats.setCheck_time(checkTime);
		
		int count = apiT_statsMapper.updateMonthStats(newStats);
		if (count > 0){
			return true;
		}else{
			return false;
		}
	}
	
	@Override
	@Transactional
	public boolean payToShipper(int stats_id,ApiT_member_pay_records payRecord) {
		ApiT_stats newStats = new ApiT_stats();
		newStats.setStats_id(stats_id);
		newStats.setStatus(3);
		String payTime = DateUtil.nowTimeToString();
		newStats.setPay_time(payTime);
		
		ApiT_stats stat = apiT_statsMapper.getShippingMonthStatsById(stats_id);
		
		//添加打款记录
		String handle_time = DateUtil.nowTimeToString();
		payRecord.setTime(handle_time);
		payRecord.setStats_id(stats_id);
		payRecord.setType(1);//1:给配送员打款
		payRecord.setUser_id(stat.getShipper_id());
		apiT_member_pay_recordsMapper.insertT_member_pay_record(payRecord);
		
		int count = apiT_statsMapper.updateMonthStats(newStats);
		if (count > 0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public List<ApiT_stats> checkedStatsList(ApiT_stats conditions, PageInfo pageInfo) {
		return apiT_statsMapper.checkedShipperMonthStatListPage(conditions, pageInfo);
	}

	@Override
	@Transactional
	public Map<String,String> updateStatStatus(int stats_id, int type,double money) {
		Map<String,String> result = new HashMap<String, String>();
			ApiT_stats aStat = apiT_statsMapper.getStatsById(stats_id); 
            if (aStat == null){
            	result.put("error", "-2");
            	result.put("information", "纪录不存在");
            	return result;
            }
            
            //Double totalMoeny = aStat.getMoney();
            Double reMoney = aStat.getReserve_money().doubleValue();
            Double on_delivery_money = aStat.getOn_delivery_money().doubleValue();
            Double cash_term_money = aStat.getCash_term_money().doubleValue();
            Double shouldMoney = Math.abs(ArithUtil.sub(on_delivery_money, cash_term_money));
        	if (money != shouldMoney){//输入的金额与充值或结算的金额不对
            	result.put("error", "-3");
            	result.put("information", "输入的金额有误！");
            	return result;
        	}
        	ApiT_shipper_account oldShipperAccount = apiT_shipper_accountMapper.findShipperById(aStat.getShipper_id());
        	ApiT_shipper_account newShipperAccount = new ApiT_shipper_account();
        	newShipperAccount.setUser_id(aStat.getShipper_id());
        	if (type == 1){//充值
            	newShipperAccount.setMoney(oldShipperAccount.getMoney().add(Util.getBigDecimal(money+"")));
            	//newShipperAccount.setOrder_cash(0.0);
        	}if (type == 2){//结算
            	newShipperAccount.setMoney(oldShipperAccount.getMoney().subtract(Util.getBigDecimal(money+"")));
        	}
        	newShipperAccount.setOrder_cash(oldShipperAccount.getOrder_cash().subtract(Util.getBigDecimal(on_delivery_money.toString())) );//重置配送员帐户中货到付款的金额
        	apiT_shipper_accountMapper.updateShipperAccount(newShipperAccount);
        	
			ApiT_stats newStats = new ApiT_stats();
			newStats.setStats_id(stats_id);
			String handleTime = DateUtil.nowTimeToString();
			newStats.setHandle_time(handleTime);
			newStats.setHandle_status(type);
			
			int count = apiT_statsMapper.updateStats(newStats);
			if (count > 0){
				result.put("error", "0000");
            	result.put("information", "操作成功");
			}
		    return result;
	}
	
	@Override
	@Transactional
	public Map<String,String> updateStationStatStatus(int stats_id, int type,double money) {
		Map<String,String> result = new HashMap<String, String>();
			ApiT_stats aStat = apiT_statsMapper.getStationtatById(stats_id); 
            if (aStat == null){
            	result.put("error", "-2");
            	result.put("information", "纪录不存在");
            	return result;
            }
            
            if (aStat.getHandle_status() >0){
            	result.put("error", "-3");
            	result.put("information", "已处理成功");
            	return result;
            }
            
            ApiT_user_admin userAdmin = apiT_user_adminMapper.getStationRoleAdmin(aStat.getCityId());
            if (userAdmin == null) {
            	result.put("error", "-4");
            	result.put("information", "暂无站长,请先添加站长");
            	return result;
            }
            
			ApiT_stats newStats = new ApiT_stats();
			newStats.setStats_id(stats_id);
			String payTime = DateUtil.nowTimeToString();
			newStats.setPay_time(payTime);
			newStats.setHandle_status(type);
			newStats.setStation_name(userAdmin.getTrue_name());
			
			int count = apiT_statsMapper.updateStationStats(newStats);
			if (count > 0){
				result.put("error", "0000");
            	result.put("information", "操作成功");
			}
			
			return result;
	}

	@Override
	public ApiT_stats getStatById(int stats_id) {
		return apiT_statsMapper.getStatsById(stats_id);
	}

	@Override
	public List<ApiT_stats> shopMonthShippingList(ApiT_stats conditions, PageInfo pageInfo) {
		return apiT_statsMapper.shopMonthShippingListPage(conditions, pageInfo);
	}

	@Override
	public ApiT_stats getShopMonthStatById(int stats_id) {
		return apiT_statsMapper.getShopMonthStatById(stats_id);
	}

	@Override
	@Transactional
	public Map<String, String> payMonthMonyToShop(int stats_id,ApiT_shops_pay_records payRecord) {
		Map<String,String> result = new HashMap<String,String>();
		ApiT_stats stat = apiT_statsMapper.getShopMonthStatById(stats_id);
		if (stat == null){
			result.put("error", "-2");
			result.put("information", "纪录不存在");
			return result ;
		}
		if (stat.getHandle_status() == 1){
			result.put("error", "-3");
			result.put("information", "已经打款成功,请刷新");
			return result ;
		}
		int shopId = stat.getShop_id();
		double money = stat.getMoney().doubleValue();//要打款的钱
		ApiShop shop = apiShopsMapper.findShopByCid(shopId+"");
		
		/*if (shop.getCashMoney() < money){//商家余额小于打款的金额
			result.put("error", "-4");
			result.put("information", "商家余额不足" + money);
			result.put("cashMoney", shop.getCashMoney()+"");
			return result;
		}*/
		
	
		
		//更新商铺余额
		ApiShop newShop = new ApiShop();
		newShop.setcId(shop.getcId());
		double finalMoney = shop.getCashMoney() - money;
		newShop.setCashMoney(finalMoney > 0 ?  finalMoney : 0);
		apiShopsMapper.updatShopInfo(newShop);
		
		//添加打款记录
		String handle_time = DateUtil.nowTimeToString();
//		payRecord.setAfter_money(finalMoney);
		payRecord.setTime(handle_time);
		payRecord.setStats_id(stats_id);
		payRecord.setType(1);//1:商家月结打款
		payRecord.setShop_id(shopId);
		payRecord.setNum(new Date().getTime() + shopId+"");
		apiT_shop_pay_recordsMapper.insertT_shop_pay_record(payRecord);
		
		//更新打款状态
		ApiT_stats newStat = new ApiT_stats();
		newStat.setStats_id(stats_id);
		newStat.setPay_time(DateUtil.nowTimeToString());
		newStat.setHandle_status(1);
		apiT_statsMapper.updateShopMonthStats(newStat);
		
		result.put("error", "0000");
		result.put("information", "打款成功");
		
		return result;
	}

	@Override
	public List<ApiT_stats> shopWeekShippingList(ApiT_stats conditions, PageInfo pageInfo) {
		return apiT_statsMapper.shopWeekShippingListPage(conditions, pageInfo);
	}
	
	
	@Override
	public List<ApiT_stats> dayStationStatList(ApiT_stats conditions, PageInfo pageInfo) {
		return apiT_statsMapper.dayStationStatListPage(conditions, pageInfo);
	}
	

	@Override
	public ApiT_stats getShopWeekStatById(int stats_id) {
		return apiT_statsMapper.getShopWeekStatById(stats_id);
	}
	
	@Override
	public ApiT_stats getStationStatById(int stats_id) {
		return apiT_statsMapper.getStationtatById(stats_id);
	}

	@Override
	@Transactional
	public Map<String, String> payWeekMonyToShop(int stats_id,ApiT_shops_pay_records payRecord) {
		Map<String,String> result = new HashMap<String,String>();
		ApiT_stats stat = apiT_statsMapper.getShopWeekStatById(stats_id);
		if (stat == null){
			result.put("error", "-2");
			result.put("information", "纪录不存在");
			return result ;
		}
		if (stat.getHandle_status() == 1){
			result.put("error", "-3");
			result.put("information", "已经打款成功,请刷新");
			return result ;
		}
		int shopId = stat.getShop_id();
		double money = stat.getMoney().doubleValue();//要打款的钱
		ApiShop shop = apiShopsMapper.findShopByCid(shopId+"");
		
		/*if (shop.getCashMoney() < money){//商家余额小于打款的金额
			result.put("error", "-4");
			result.put("information", "商家余额不足" + money);
			result.put("cashMoney", shop.getCashMoney()+"");
			return result;
		}*/
		
		//更新商铺余额
		ApiShop newShop = new ApiShop();
		newShop.setcId(shop.getcId());
		double finalMoney = shop.getCashMoney() - money;
		newShop.setCashMoney(finalMoney > 0 ?  finalMoney : 0);
		apiShopsMapper.updatShopInfo(newShop);
		
		//更新打款状态
		ApiT_stats newStat = new ApiT_stats();
		newStat.setStats_id(stats_id);
		newStat.setPay_time(DateUtil.nowTimeToString());
		newStat.setHandle_status(1);
		apiT_statsMapper.updateShopWeekStats(newStat);
		
		//添加打款记录
		String handle_time = DateUtil.nowTimeToString();
		// payRecord.setAfter_money(finalMoney);
		payRecord.setTime(handle_time);
		payRecord.setStats_id(stats_id);
		payRecord.setType(2);//2:商家周结打款
		payRecord.setShop_id(shopId);
		payRecord.setNum(new Date().getTime() + shopId+"");
		apiT_shop_pay_recordsMapper.insertT_shop_pay_record(payRecord);
		
		result.put("error", "0000");
		result.put("information", "打款成功");
		
		return result;
	}

}
